package com.concurrent.frame.core;

import com.concurrent.frame.mark.ThreadSafe;
import com.concurrent.frame.pojo.DelayVo;

import javax.print.attribute.standard.JobName;
import java.util.concurrent.DelayQueue;

/**
 * 延迟队列: 保存任务结果,一定时间,定时销毁
 */
@ThreadSafe
public class CheckJobProcessor {
    //任务已经完成,等待过期
    private static DelayQueue<DelayVo<String>> queue = new DelayQueue<DelayVo<String>>();
    //单例模式
    private CheckJobProcessor() {
    }
    private static  class CheckJobProcessorSub{
        public static CheckJobProcessor checkJobProcessor = new CheckJobProcessor();
    }
    public static CheckJobProcessor getInstance(){
        return CheckJobProcessorSub. checkJobProcessor;
    }
    //单例模式
    //处理任务中过任务的线程
    private static class RemoveDelayJob implements Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    //获取已经过期的任务
                    DelayVo<String> item = queue.take();
                    String jobName = (String) item.getDate();
                    //移除
                     ResourceRegisterPool.getMap().remove(jobName);
                    System.out.println("Job["+jobName+"]: 达到过期时间,已经从PendingJobPool.jonInfoMap中移除");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }
    //任务完成后放入队列,经过expireTime销毁
    public void putJob(String jobName,long expireTime){
        DelayVo<String> item = new DelayVo<String>(expireTime, jobName);
        queue.offer(item);
        System.out.println("Job["+jobName+"]:已经放入过期队列,过期时长:"+expireTime );
    }
    static {
        Thread thread = new Thread(new RemoveDelayJob());
        thread.setDaemon(true);//开启守护线程
        thread.start();
        System.out.println("RemoveDelayJob任务过期检查线程开启............");
    }
}